﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MessagingMediator
{
    public class GeneralMessaging
    {
        MessageQueue _startupQueue;
        MessageQueue _sendToServer;
        MessageQueue _receiveFromServer;
        List<Consumer> _infoScreenConsumers;

        public GeneralMessaging()
        {
            _startupQueue = CreateQueue("announce-startup");
            _sendToServer = CreateQueue("info-to-server");
            _receiveFromServer = CreateQueue("server-to-info");

            _infoScreenConsumers = new List<Consumer>();
        }

        public void InitializeMessaging()
        {
            Console.WriteLine("Initializing Messaging");
            Console.WriteLine("Initializing StartupQueue");
            _startupQueue.ReceiveCompleted += _startupQueue_ReceiveCompleted;
            _startupQueue.BeginReceive();
            Console.WriteLine("Initialized BeginReceive on StartupQueue");

            Console.WriteLine("Initializing ReceiveFromServer Queue");
            _receiveFromServer.ReceiveCompleted += _receiveFromServer_ReceiveCompleted;
            _receiveFromServer.BeginReceive();
            Console.WriteLine("Initialized BeginReceive on ReceiveFromServer");
        }

        private void _receiveFromServer_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            MessageQueue mq = (MessageQueue)sender;
            Message message = mq.EndReceive(e.AsyncResult);
            message.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });

            //Gets queue name from message somehow!
            MessageQueue replyChannel = CreateQueue("InsertQueueNameHere");

            replyChannel.Send(message);

            mq.BeginReceive();
        }

        private void _startupQueue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            MessageQueue mq = (MessageQueue)sender;
            Message message = mq.EndReceive(e.AsyncResult);
            message.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });

            Consumer newConsumer = new Consumer(CreateQueue(message.Body.ToString()), _sendToServer);
            _infoScreenConsumers.Add(newConsumer);

            mq.BeginReceive();
        }

        private MessageQueue CreateQueue(string queueName)
        {
            // Create queue
            string path = @".\Private$\" + queueName;
            MessageQueue mq = new MessageQueue();

            if (MessageQueue.Exists(path))
                mq = new MessageQueue(path);
            else
                mq = MessageQueue.Create(path);

            return mq;
        }
    }
}
